package com.yao.grpcdemo.grpc;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;

import java.io.IOException;

/**
 * 监听应用启动事件，启动server
 *
 * @author yys1892
 */
public class GRpcApplicationEventListener implements ApplicationListener<ApplicationStartedEvent>, ApplicationContextAware {
    private final Logger logger = LoggerFactory.getLogger(GRpcApplicationEventListener.class);
    private ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        ServerBuilder bean = applicationContext.getBean(ServerBuilder.class);
        Server server = bean.build();
        try {
            // 启动GRpcServer
            server.start();
            // jvm关闭时关闭GRpcServer
            Runtime.getRuntime().addShutdownHook(new Thread(server::shutdown));
            logger.info("start GRpc server ...");
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
